package com.xln.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
public class FileUploadUtil {
    
    // 上传目录
    private static final String UPLOAD_DIR = "uploads/";
    
    /**
     * 上传文件
     * @param file 文件
     * @param uploadPath 上传路径
     * @return 文件访问URL
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file, String uploadPath) throws IOException {

//      获取日期创建的目录
        String dateDir = uploadPath+ "\\" + DateUtil.getCurrentDateDir();

        // 创建上传目录
        Path uploadDir = Paths.get(dateDir);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
        
        // 保存文件
        Path filePath = uploadDir.resolve(uniqueFilename);
        Files.write(filePath, file.getBytes());
        log.info("文件保存成功: {}", filePath);
        
        // 返回访问URL
        return "/uploads/" + DateUtil.getCurrentDateDir() + "/" + uniqueFilename;
    }
}
